package org.leon;

import java.io.IOException;
import java.io.InputStream;

/**
 * Http 请求数据封装成 Request 对象
 */
public class Request {

    private String method;

    private String url;

    private String host;


    public Request() {}

    public Request(InputStream inputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        byte[] content = new byte[count];
        inputStream.read(content);


        /*
            请求内容类似这种格式
            GET /demo/query HTTP/1.1
            Host: www.baidu.com
            Connection: keep-alive
            Pragma: no-cache
            Cache-Control: no-cache
            Upgrade-Insecure-Requests: 1
            User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36
            Sec-Fetch-Dest: document
        */
        String requestContext = new String(content);

        // 按换行拆分
        String[] contextArrays = requestContext.split("\\n");
        // 取第一行，然后按空格拆分，获取请求方法
        String[] requestInfo = contextArrays[0].split(" ");
        // 取第二行，按冒号拆分，获取host
        String[] hostInfo = contextArrays[1].split(":");

        this.method = requestInfo[0].trim();
        this.url = requestInfo[1].trim();
        this.host = hostInfo[1].trim();
        if (this.host.equals("127.0.0.1")) {
            this.host = "localhost";
        }

        //inputStream.close();
    }

    public String getMethod() {
        return method;
    }

    public String getUrl() {
        return url;
    }

    public String getHost() {
        return host;
    }
}
